package com.hs.wdss.action.produce;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.hs.auth.model.HsAccount;
import com.hs.core.action.BaseAction;
import com.hs.core.cache.GlobalParamCache;
import com.hs.core.db.DBMgr;
import com.hs.core.db.QueryPage;
import com.hs.core.utils.PageParam;
import com.hs.core.utils.PageUtil;
import com.hs.core.utils.TimeUtil;
import com.hs.core.utils.Tools;
import com.hs.core.utils.UUIDGenerator;
import com.hs.wdss.model.WdssCuremethod;
import com.hs.wdss.model.WdssDisinfo;
import com.hs.wdss.model.WdssFile;
import com.hs.wdss.model.WdssPreinfo;
import com.hs.wdss.model.WdssResource;
import com.hs.wdss.service.IDataService;
 @Controller  
public class DataProController  extends BaseAction {
    /**
	 * 
	 */
	private static final long serialVersionUID = -354434172898440670L;
	private static final Logger logger = Logger.getLogger(DataProController.class);
	private IDataService dataService;
	@Autowired  
	public void setDataService(IDataService dataService) {
		this.dataService = dataService;
	}
	 /**
	  * 加工菜单
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/datapromenu.do")   
   public ModelAndView auditMenu(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid");
		 request.setAttribute("wdssid", wdssid);
		 modelMap.put("wdssid", wdssid);
		 if(!"".equals(wdssid)){
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 modelMap.put("obj", obj); 
		 }
		 return new ModelAndView("app/produce/datapromenu",modelMap);
		 
	 }
	 /**
	  * 医案信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/dataprodis.do")   
   public ModelAndView dataproDis(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid");
		 if(!"".equals(wdssid)){
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 modelMap.put("obj", obj); 
			 WdssResource rsobj = (WdssResource)this.dataService.findByID(WdssResource.class,new Long(obj.getDsid()));
			 modelMap.put("rsobj", rsobj); 
		 }
		 
		 List datalist = this.getDbo(request).queryList("select TO_CHAR(ID) AS ID,STANDARDNAME||'('||SYNONYMS||')' AS VALUE from WDSS_STANDARD where CATEGORY='病名' ORDER BY STANDARDNAME ", null);
		 modelMap.put("disnamelist", datalist);
		 
		 
		 return new ModelAndView("app/produce/dataprodis",modelMap);
		 
	 }
	 /**
	  * 基本信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/dataprobasic.do")   
   public ModelAndView dataproBasic(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid");
		 if(!"".equals(wdssid)){
			 //List obj = this.dataService.findList("select a from WdssUserinfo a  where a.disid=" + wdssid);
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 modelMap.put("obj", obj); 
		 }
		 return new ModelAndView("app/produce/dataprobasic",modelMap);
		 
	 }
	 /**
	  * 并发症
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/dataproPara.do")   
   public ModelAndView dataproPara(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid");
		 if(!"".equals(wdssid)){
			// List obj = this.dataService.findList("select a from WdssParainfo a  where a.disid=" + wdssid);
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 modelMap.put("obj", obj); 
		 }
		 return new ModelAndView("app/produce/datapropara",modelMap);
		 
	 }
	 /**
	  * 病因信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/dataproDiscause.do")   
   public ModelAndView dataproDiscause(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid");
		 if(!"".equals(wdssid)){
			 //List obj = this.dataService.findList("select a from WdssDiscauseinfo a  where a.disid=" + wdssid);
			 //List obj = this.getDbo(request).queryList("select * from wdss_userinfo where disid=?", new Object[]{wdssid});
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 modelMap.put("obj", obj); 
		 }
		
		 return new ModelAndView("app/produce/dataprodiscause",modelMap);
		 
	 }
	 /**
	  * 症状信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/dataproPtom.do")   
   public ModelAndView dataproPtom(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid");
		 if(!"".equals(wdssid)){
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 modelMap.put("obj", obj); 
		 }
		 return new ModelAndView("app/produce/dataproptom",modelMap);
		 
	 }
	 /**
	  * 证候信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/dataproSym.do")   
   public ModelAndView dataproSym(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid");
		 if(!"".equals(wdssid)){
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 modelMap.put("obj", obj); 
//			 String sql = "select distinct symtype from wdss_ptominfo where disid="+wdssid;
//			 List ptomlist = DBMgr.getDbUtilInst().queryList(sql, null);
//			 modelMap.put("ptomlist", ptomlist); 
			 List cureselect = this.getDbo(request).queryList("select TO_CHAR(ID) AS ID,(select STANDARDNAME||'('||SYNONYMS||')'  from WDSS_STANDARD where id=CURENAME) AS VALUE from WDSS_CUREMETHOD where DISID=?", new Object[]{wdssid});
			 List symselect = this.getDbo(request).queryList("select TO_CHAR(ID) AS ID,(select STANDARDNAME||'('||SYNONYMS||')'  from WDSS_STANDARD where id=SYMNAME) AS VALUE from WDSS_SYMINFO where DISID=?", new Object[]{wdssid});
			 modelMap.put("cureselect", cureselect);
			 modelMap.put("symselect", symselect);
		 }
		 List symlist = this.getDbo(request).queryList("select TO_CHAR(ID) AS ID,STANDARDNAME||'('||SYNONYMS||')' AS VALUE from WDSS_STANDARD where CATEGORY='证候' ORDER BY STANDARDNAME ", null);
		 modelMap.put("symlist", symlist);
		 List curelist = this.getDbo(request).queryList("select TO_CHAR(ID) AS ID,STANDARDNAME||'('||SYNONYMS||')' AS VALUE from WDSS_STANDARD where CATEGORY='治法' ORDER BY STANDARDNAME ", null);
		 modelMap.put("curelist", curelist);
		 return new ModelAndView("app/produce/dataprosym",modelMap);
		 
	 }
	 /**
	  * 方剂信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/dataproPre.do")   
   public ModelAndView dataproPre(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid");
		 if(!"".equals(wdssid)){
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 modelMap.put("obj", obj); 
			 List cureselect = this.getDbo(request).queryList("select TO_CHAR(ID) AS ID,(select STANDARDNAME||'('||SYNONYMS||')'  from WDSS_STANDARD where id=CURENAME) AS VALUE from WDSS_CUREMETHOD where DISID=?", new Object[]{wdssid});
 			 modelMap.put("cureselect", cureselect);
		 }
		 return new ModelAndView("app/produce/datapropre",modelMap);
		 
	 }
	 /**
	  * 数据加工主页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping("/produce/datafinishlist.do")   
     public ModelAndView datafinishlist(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		    PageParam pageParam = new  PageParam(request,"produce/datafinishlist.do");
			StringBuffer buffer = new StringBuffer();

//		  /** 排序部分*/
			StringBuffer orderByStr = new StringBuffer(" ");
			//	//排序部分
			String orderName = request.getParameter("orderName");
			String orderNum = request.getParameter("orderNum"); 
			String bookname = request.getParameter("bookname");
			String nianfen = request.getParameter("nianfen"); 
			 if(StringUtils.isNotBlank(orderName)){
			    	if("1".equals(orderNum)){
			    		orderByStr.append(orderName).append(" asc");
			    	}
			    	if("2".equals(orderNum)){
			    		orderByStr.append(orderName).append(" desc");
			    	}
			    }else{
			    	orderByStr.append("a.publishdate").append(" desc");
			    	orderName = "a.publishdate";
			    	orderNum = "2";
			    }
			 request.setAttribute("orderName", orderName); 
			 request.setAttribute("orderNum", orderNum); 
			 pageParam.getConditionMap().put("orderName", orderName);
			 pageParam.getConditionMap().put("orderNum", orderNum);
			 HsAccount accinfo = this.getCurrentuser(request);
			 /** 排序部分*/
		    //排序结束
			PageUtil pageUtil = null;
			StringBuffer searchBuffer = new StringBuffer(" select a from WdssDisinfo a  where a.dataproducer.id =").append(accinfo.getId());
			String prename = request.getParameter("prename"); 
			String precomfrom = request.getParameter("precomfrom"); 
			 
			if(StringUtils.isNotBlank(bookname)){
				searchBuffer.append(" and (a.bookname like '%").append(bookname).append("%') ");
				pageParam.getConditionMap().put("bookname", bookname);
				request.setAttribute("bookname", bookname);
			}  
			if(StringUtils.isNotBlank(nianfen)){
				searchBuffer.append(" and a.publishdate like'%").append(nianfen).append("%'");
				pageParam.getConditionMap().put("publishdate", nianfen);
				request.setAttribute("nianfen", nianfen);
			}  
			searchBuffer.append(" ORDER BY   ").append(" a.state");
			Map data = new HashMap();
 
			pageParam.setSearchSql(searchBuffer.toString());
			pageUtil = dataService.getPageList(pageParam); 
			modelMap.put("prodatalist", pageUtil);  
 		 return new ModelAndView("app/produce/finishdatalist",modelMap);
		 
	 } 
	 /**
	  * 图片上传主页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/uploadFile.do", method = RequestMethod.GET)   
     public ModelAndView uploadFile(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         String id = request.getParameter("id");
         WdssDisinfo obj = (WdssDisinfo)dataService.findByID(WdssDisinfo.class, new Long(id));
         modelMap.put("obj", obj);
		 return new ModelAndView("app/produce/fileUpload",modelMap);
		 
	 }
	 /**
	  * 数据加工主页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping("/produce/dataprolist.do")   
     public ModelAndView waitProlist(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		    PageParam pageParam = new  PageParam(request,"produce/dataprolist.do");
			StringBuffer buffer = new StringBuffer();

//		  /** 排序部分*/
			StringBuffer orderByStr = new StringBuffer(" order by  ");
			//	//排序部分
			String orderName = request.getParameter("orderName");
			String orderNum = request.getParameter("orderNum"); 
			String disname = request.getParameter("disname");
			String discode = request.getParameter("discode");
			String state = request.getParameter("state");
			String dstype = request.getParameter("dstype");
			 request.setAttribute("dstype", dstype); 
			if(StringUtils.isEmpty(state)){
				state = "0";
			}
			 if(StringUtils.isNotBlank(orderName)){
			    	if("1".equals(orderNum)){
			    		orderByStr.append(orderName).append(" asc");
			    	}
			    	if("2".equals(orderNum)){
			    		orderByStr.append(orderName).append(" desc");
			    	}
			    }else{
			    	orderByStr.append("state").append(" desc");
			    	orderName = "state";
			    	orderNum = "2";
			    }
			 request.setAttribute("orderName", orderName); 
			 request.setAttribute("orderNum", orderNum); 
			 /** 排序部分*/
		    //排序结束

			HsAccount accinfo = this.getCurrentuser(request);
			StringBuffer searchBuffer = null;
			Map authMap = (Map)request.getSession().getAttribute("USERPOWER_"+accinfo.getId());
			boolean role3 = (authMap.get("WDSS_ROLE03")!=null);
			logger.debug("role3:" + role3);

			if(StringUtils.isEmpty(dstype))
				dstype = "0";
            if(null == dstype || "0".equals(dstype)){
            	searchBuffer = new StringBuffer(" select ds.discode,ds.id,ds.dsid,rs.bookname,rs.author,(select STANDARDNAME from WDSS_STANDARD where id =ds.disname) as disname ,(select username from hs_userinfo a where ds.dataproducer=a.id) as username,ds.state,'古代医案' as dstype ");
    			searchBuffer.append("from wdss_disinfo ds,wdss_resource rs  ");
    			searchBuffer.append("where rs.dstype=1 and ds.dsid = rs.id  ");
    			
    			if("99".equals(state)){
    				searchBuffer.append(" and ds.dataproducer="+accinfo.getId() ); 
    			}else if("2".equals(state)){
    				if(role3){
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    					searchBuffer.append(" and ds.dataproducer=").append(accinfo.getId() ).append(" ");
    				}else{ 
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    				} 
    			}else if("0".equals(state)){
    				searchBuffer.append(" and ds.state='").append(state).append("'");
    			}else if("3".equals(state)|| "4".equals(state)){
    				if(role3){
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    					searchBuffer.append(" and ds.dataproducer=").append(accinfo.getId() ).append(" ");
    				}else{ 
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    				}
    			}else if("all".equals(state)){
    			}else{
    				searchBuffer.append(" and ds.dataproducer="+accinfo.getId() ).append(" and ds.state='").append(state).append("'");
    			}
    			 
    			
    			if(StringUtils.isNotBlank(disname)){
    				searchBuffer.append(" and (ds.disname like '%").append(disname).append("%' )");
    				request.setAttribute("disname", disname);
    			}   
    			if(StringUtils.isNotBlank(discode)){
    				searchBuffer.append(" and (ds.discode like '%").append(discode).append("%' )");
    				request.setAttribute("discode", discode);
    			}   
				searchBuffer.append(" union ");
				searchBuffer.append(" select ds.discode,ds.id,ds.dsid,rs.maganame as bookname ,rs.author,(select STANDARDNAME from WDSS_STANDARD where id =ds.disname) as disname ,(select username from hs_userinfo b where ds.dataproducer=b.id) as username,ds.state,'现代医案' as dstype ");
				searchBuffer.append("from wdss_disinfo ds,wdss_resource rs ");
				searchBuffer.append("where rs.dstype=2 and  ds.dsid = rs.id ");
				if("99".equals(state)){
    				searchBuffer.append(" and ds.dataproducer="+accinfo.getId() ); 
    			}else if("0".equals(state)){
    				searchBuffer.append(" and ds.state='").append(state).append("'");
    			}else if("2".equals(state)){
    				if(role3){
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    					searchBuffer.append(" and ds.dataproducer=").append(accinfo.getId() ).append(" ");
    				}else{ 
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    				} 
    			}else if("all".equals(state)){
    			}else if("3".equals(state)|| "4".equals(state)){
    				if(role3){
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    					searchBuffer.append(" and ds.dataproducer=").append(accinfo.getId() ).append(" ");
    				}else{ 
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    				}
    			}else{
    				searchBuffer.append(" and ds.dataproducer="+accinfo.getId() ).append(" and ds.state='").append(state).append("'");
    			}
				//and ds.dsid = rs.id and (ds.dataproducer="+accinfo.getId() ).append(" or ds.state='").append(state).append("')");
				if(StringUtils.isNotBlank(disname)){
					searchBuffer.append(" and (ds.disname like '%").append(disname).append("%' )");
					request.setAttribute("disname", disname);
				}  
				if(StringUtils.isNotBlank(discode)){
    				searchBuffer.append(" and (ds.discode like '%").append(discode).append("%' )");
    				request.setAttribute("discode", discode);
    			}   
				searchBuffer.append(orderByStr);
            }
            if("1".equals(dstype)){
            	searchBuffer = new StringBuffer(" select ds.discode,ds.id,ds.dsid,rs.bookname,rs.author,(select STANDARDNAME from WDSS_STANDARD where id =ds.disname) as disname ,(select username from hs_userinfo a where ds.dataproducer=a.id) as username,ds.state,'古代医案' as dstype ");
    			searchBuffer.append("from wdss_disinfo ds,wdss_resource rs  ");
    			searchBuffer.append("where rs.dstype=1 and ds.dsid = rs.id ");
    			if("99".equals(state)){
    				searchBuffer.append(" and ds.dataproducer="+accinfo.getId() ); 
    			}else if("2".equals(state)){
    				if(role3){
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    					searchBuffer.append(" and ds.dataproducer=").append(accinfo.getId() ).append(" ");
    				}else{ 
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    				} 
    			}else if("0".equals(state)){
    				searchBuffer.append(" and ds.state='").append(state).append("'");
    			}else if("all".equals(state)){
    			}else if("3".equals(state)|| "4".equals(state)){
    				searchBuffer.append(" and ds.state='").append(state).append("'");
    			}else{
    				searchBuffer.append(" and ds.dataproducer="+accinfo.getId() ).append(" and ds.state='").append(state).append("'");
    			}
    			//and (ds.dataproducer="+accinfo.getId() ).append(" or ds.state='").append(state).append("')");
    			if(StringUtils.isNotBlank(disname)){
    				searchBuffer.append(" and (ds.disname like '%").append(disname).append("%' )");
    				request.setAttribute("disname", disname);
    			}  
    			if(StringUtils.isNotBlank(discode)){
    				searchBuffer.append(" and (ds.discode like '%").append(discode).append("%' )");
    				request.setAttribute("discode", discode);
    			}   
    			searchBuffer.append(orderByStr);
            }
            if("2".equals(dstype)){
            	searchBuffer = new StringBuffer(" select ds.discode,ds.id,ds.dsid,rs.maganame as bookname ,rs.author,(select STANDARDNAME from WDSS_STANDARD where id =ds.disname) as disname ,(select username from hs_userinfo b where ds.dataproducer=b.id) as username,ds.state,'现代医案' as dstype ");
				searchBuffer.append("from wdss_disinfo ds,wdss_resource rs ");
				searchBuffer.append("where rs.dstype=2 and ds.dsid = rs.id ");
				//and (ds.dataproducer="+accinfo.getId() ).append(" or ds.state='").append(state).append("')");
				if("99".equals(state)){
    				searchBuffer.append(" and ds.dataproducer="+accinfo.getId() ); 
    			}else if("0".equals(state) ){
    				searchBuffer.append(" and ds.state='").append(state).append("'");
    			}else if("2".equals(state)){
    				if(role3){
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    					searchBuffer.append(" and ds.dataproducer=").append(accinfo.getId() ).append(" ");
    				}else{ 
    					searchBuffer.append(" and ds.state='").append(state).append("'");
    				}
    			}else if("all".equals(state)){
    			}else if("3".equals(state) || "4".equals(state)){
    				searchBuffer.append(" and ds.state='").append(state).append("'");
    			}else{
    				searchBuffer.append(" and ds.dataproducer="+accinfo.getId() ).append(" and ds.state='").append(state).append("'");
    			}
				if(StringUtils.isNotBlank(disname)){
					searchBuffer.append(" and (ds.disname like '%").append(disname).append("%' )");
					request.setAttribute("disname", disname);
				}  
				if(StringUtils.isNotBlank(discode)){
    				searchBuffer.append(" and (ds.discode like '%").append(discode).append("%' )");
    				request.setAttribute("discode", discode);
    			}   
				searchBuffer.append(orderByStr);
            }
//			if(StringUtils.isNotBlank(state) && !"99".equals(state)){
//				searchBuffer.append(" and ds.state='").append(state).append("'");
//				request.setAttribute("state", state);
//			}  
//			//查询待审核的期刊
//			searchBuffer.append(" union ");
//			searchBuffer.append(" select ds.id,ds.dsid,rs.maganame as bookname ,rs.author,ds.disname,(select username from hs_userinfo where ds.dataproducer=us.id) as username,ds.state,'现代医案' as dstype ");
//			searchBuffer.append("from wdss_disinfo ds,wdss_resource rs  ");
//			searchBuffer.append("where rs.dstype=2 and ds.dsid = rs.id   and ds.state=2");
//			if(StringUtils.isNotBlank(disname)){
//				searchBuffer.append(" and (ds.disname like '%").append(disname).append("%' )");
//				request.setAttribute("disname", disname);
//			}  
//			if(StringUtils.isNotBlank(state) && !"99".equals(state)){
//				searchBuffer.append(" and ds.state='").append(state).append("'");
//				request.setAttribute("state", state);
//			}  
//			//查询待审核的书籍
//			searchBuffer.append(" union ");
//			searchBuffer.append(" select ds.id,ds.dsid,rs.bookname,rs.author,ds.disname,(select username from hs_userinfo where ds.dataproducer=us.id) as username,ds.state,'古代医案' as dstype ");
//			searchBuffer.append("from wdss_disinfo ds,wdss_resource rs ");
//			searchBuffer.append("where rs.dstype=1 and ds.dsid = rs.id   and ds.state=2");
//			if(StringUtils.isNotBlank(disname)){
//				searchBuffer.append(" and (ds.disname like '%").append(disname).append("%' )");
//				request.setAttribute("disname", disname);
//			}  
//			if(StringUtils.isNotBlank(state) && !"99".equals(state)){
//				searchBuffer.append(" and ds.state='").append(state).append("'");
//				request.setAttribute("state", state);
//			} 
			
			//System.out.print("buffersql:" + searchBuffer.toString());

			Map conditionmap = new HashMap();
	         conditionmap.put("orderName", orderName);
	         conditionmap.put("orderNum", orderNum);
	         conditionmap.put("disname", disname);
	         conditionmap.put("discode", discode);
	         conditionmap.put("dstype", dstype);
	         conditionmap.put("state", state);
	         logger.debug("sql:" + searchBuffer);
			 String perPageCount = request.getParameter("perPageCount");
		     QueryPage qp = new QueryPage(request,request.getContextPath()+"/produce/dataprolist.do",searchBuffer.toString(),conditionmap); 
		     if(null == perPageCount || "".equals(perPageCount)){
				qp.setPerPageCount(15);
			 }else {
				qp.setPerPageCount(Integer.parseInt(perPageCount));
		     }
		    qp.query();  
		    String pagenum =  qp.getCurrentPageNo() + "";
		    String pagecount = qp.getPerPageCount() + "";
		    modelMap.put("pagenum", pagenum);
		    modelMap.put("pagecount", pagecount);
		    modelMap.put("pagestr", qp.getPageStr());
		    modelMap.put("datalist", qp.getDataList());
		    modelMap.put("allsql", searchBuffer.toString());
		    modelMap.put("state", state);
		    modelMap.put("disname", disname);
		    modelMap.put("discode", discode);
 
 		 return new ModelAndView("app/produce/datalist",modelMap);
		 
	 } 
	 /**
	  * 增加医案
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/addDis.do", method = RequestMethod.GET)   
     public ModelAndView addDis(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 return new ModelAndView("app/produce/dataframe",modelMap);
	 }
	 /**
	  * 数据加工页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/dataPro.do", method = RequestMethod.GET)   
     public ModelAndView dataPro(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid");
		 if(!"".equals(wdssid)){
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 HsAccount accinfo = this.getCurrentuser(request);
			 if(null != accinfo){
				 Long accid = accinfo.getId();
				 this.getDbo(request).update("update WDSS_DISINFO set DATAPRODUCER=?,STATE='1' where id=?", new Object[]{accid,obj.getId()});
			 }
			 modelMap.put("obj", obj); 
		 }
		 modelMap.put("wdssid", wdssid);
		 return new ModelAndView("app/produce/dataframe",modelMap);
	 }
	 /**
	  * 查看加工结果框架页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/proResultFrame.do")   
    public ModelAndView auditlistFrame(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid"); 
		 request.setAttribute("wdssid", wdssid);
		 return new ModelAndView("app/produce/proresultframe",modelMap);
		 
	 } 
	 /**
	  * 查看加工结果中的menu
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/proresultmenu.do")   
    public ModelAndView proresultMenu(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 return new ModelAndView("app/produce/proresultmenu",modelMap);
		 
	 }
	 /**
	  * 查看加工结果中的基本信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/proresultbasic.do")   
    public ModelAndView proresultBasic(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid");
		 if(!"".equals(wdssid)){
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 modelMap.put("obj", obj); 
		 }
		 return new ModelAndView("app/produce/proresultbasic",modelMap);
		 
	 }
	 /**
	  * 查看加工结果中的医案信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/proresultInfo.do")   
    public ModelAndView proresultInfo(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid"); 
		 if(!"".equals(wdssid)){
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 modelMap.put("obj", obj); 
			 //查询疾病名称
			 List disnamelist = this.getDbo(request).queryList("select * from WDSS_STANDARD where id=?", new Object[]{obj.getDisname()});
			 if(disnamelist.size()>0){
				 Map disname = (Map)disnamelist.get(0);
				 obj.setDisname4view((String)disname.get("STANDARDNAME")); 
			 }
			 WdssResource rsobj = (WdssResource)this.dataService.findByID(WdssResource.class,new Long(obj.getDsid()));
			 modelMap.put("rsobj", rsobj); 
			 String sql = "select distinct symtype from wdss_ptominfo where disid="+wdssid;
			 List ptomlist = DBMgr.getDbUtilInst().queryList(sql, null);
			 modelMap.put("ptomlist", ptomlist); 
			 sql = "select distinct datatype from wdss_discauseinfo where disid="+wdssid;
			 List discauselist = DBMgr.getDbUtilInst().queryList(sql, null);
			 modelMap.put("discauselist", discauselist);
			 
			 List cureselect = this.getDbo(request).queryList("select TO_CHAR(ID) AS ID,STANDARDNAME||'('||SYNONYMS||')' AS VALUE from WDSS_STANDARD where id in(select CURENAME from WDSS_CUREMETHOD where DISID=?)", new Object[]{wdssid});
			 List symselect = this.getDbo(request).queryList("select TO_CHAR(ID) AS ID,STANDARDNAME||'('||SYNONYMS||')' AS VALUE from WDSS_STANDARD where id in(select SYMNAME from WDSS_SYMINFO where DISID=?)", new Object[]{wdssid});
			 modelMap.put("cureselect", cureselect);
			 modelMap.put("symselect", symselect);
			 
			 List prelist = this.getDbo(request).queryList(" select * from WDSS_PREINFO where   disid=?", new Object[]{wdssid});
			 List preselect = new ArrayList();
			 for(int i=0;i<prelist.size();i++){
			
				 Map premap = (Map)prelist.get(i);
				 System.out.println(premap);
				 String id = premap.get("id")+"";
				 String prename = (String)premap.get("prename");
				 List herblist = this.getDbo(request).queryList("select a.*  from WDSS_HERBINFO a where preid=?", new Object[]{id});
				 premap.put("herblist", herblist);
				 preselect.add(premap);
			 }
 			 modelMap.put("preselect", preselect);
			 
		 }
		 return new ModelAndView("app/produce/proresultinfo",modelMap);
		 
	 }
	 /**
	  * 查看加工结果中的方剂信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/producepre.do")   
    public ModelAndView producePre(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String cureid = request.getParameter("cureid");
		 if(!"".equals(cureid)){
			 WdssCuremethod obj = (WdssCuremethod)this.dataService.findByID(WdssCuremethod.class, new Long(cureid));
			 modelMap.put("obj", obj); 
		 }
		 return new ModelAndView("app/produce/proresultpre",modelMap);
		 
	 }
	 /**
	  * 查看加工结果中的中药信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/proresultherb.do")   
    public ModelAndView proresultHerb(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String wdssid = request.getParameter("wdssid");
		 String preid = request.getParameter("preid");
		 if(StringUtils.isNotBlank(preid)){
			 WdssPreinfo preobj = (WdssPreinfo)this.dataService.findByID(WdssPreinfo.class, new Long(preid));
			 modelMap.put("preobj", preobj); 
		 }else  if(!"".equals(wdssid)){
			 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(wdssid));
			 modelMap.put("obj", obj); 
		 }
		 return new ModelAndView("app/produce/proresultherb",modelMap);
		 
	 }
	 /**
	  * 文件加工页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/datafilePro.do", method = RequestMethod.GET)   
     public ModelAndView datafilePro(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String id = request.getParameter("id");
		 WdssDisinfo obj = (WdssDisinfo)this.dataService.findByID(WdssDisinfo.class, new Long(id));
		 modelMap.put("obj", obj);
		 String  tempsql = "select id,distype,disname from DNMS_MODERN_DIS where validsign='1'";
         List modlist = DBMgr.getDbUtilInst().queryList(tempsql,null);
         System.out.println("poiList.size()::::" + modlist.size());
         modelMap.put("modlist", modlist);
		 return new ModelAndView("app/produce/dataPro",modelMap);
		 
	 }

	 /**
	  * 原文加工
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping("/produce/fileSave.do")   
     public void fileSave(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws Exception {
		 logger.debug("enter");
			String id = request.getParameter("id");
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
			MultipartFile multipartFile = multipartRequest.getFile("bookfile");   
			String fileName = multipartFile.getOriginalFilename();  
			HsAccount accobj = this.getCurrentuser(request);
			String[] bookinfo = this.writePdfFile(multipartFile.getBytes(), fileName);
			//对于没有后缀名的文件，忽略不处理 
			WdssFile fileobj = null;
			String returnId = "";
			fileobj = new WdssFile();
			 
			fileobj.setFilename(fileName);
			fileobj.setDisid(new Long(id));
			fileobj.setUserid(accobj == null?0:accobj.getId());
			fileobj.setUploaddate(TimeUtil.getCurrentstr());
			fileobj.setFilepath(bookinfo[0]+bookinfo[1]);
			this.dataService.saveObject(fileobj);
			returnId = fileobj.getId() +"";
			response.setCharacterEncoding("UTF-8");
			StringBuffer buffer =  new StringBuffer();
			buffer.append(returnId).append("$").append("[{"); 
			buffer.append("id:'").append(returnId).append("',"); 
			buffer.append("url:'").append(fileobj.getFilepath()).append("',");  
			buffer.append("fileName:'").append(fileobj.getFilename()).append("'");
			buffer.append("}]"); 		 
	    	try {
				PrintWriter w = response.getWriter(); 
				 w.println(buffer.toString());
				 w.flush();
				 w.close();
			} catch (IOException e) {
				 throw e;
			} 
 		 
	 }
	 
	 private String[] writePdfFile(byte[] fileContent,String fileName) throws Exception{
		 String[] temp = new String[3];
			StringBuffer buffer = new StringBuffer();
			String sep = System.getProperty("file.separator");
			sep = "/"; 
			//存储路径
			String webRoot = GlobalParamCache.getInst().getParamByKey("filepath");// SystemUtil.getWebappRoot().getPath() + sep +  "upload";//SWFConvertUtil.getParamMap("filepath");// 
//			if(null != filesavepath)
//				webRoot = filesavepath;
			String middlePath = Tools.buildFileSubdirectory();
			String fileSaveUUID = UUIDGenerator.getUUID();
			String fullPath = webRoot + sep + middlePath;
			buffer.append(middlePath).append(sep);
			 
			logger.debug("fullPath:" + fullPath);
			File rootDir = new File(webRoot); 
			File directory = null;
			if (!rootDir.exists()) {
				rootDir.mkdirs(); 
			} 
			directory = new File(rootDir, middlePath);
			if(!directory.exists() && !directory.mkdirs()){
				logger.error("创建文件存储路径失败【" + directory.getAbsolutePath() + "】");
			}  
			 
			StringBuffer fileLocation = new StringBuffer(webRoot);
			StringBuffer fileFullPath = new StringBuffer();
			fileLocation.append(middlePath); 
			fileLocation.append(sep); 
			
			fileFullPath.append(middlePath); 
			fileFullPath.append(sep); 
			String fileSaveName = "";
			int pos = fileName.lastIndexOf('.');
			if (pos == -1) {
				fileSaveName = fileSaveUUID;
			} else {
				fileSaveName = fileSaveUUID + fileName.substring(pos);
			}
			//buffer.append(fileSaveName);
			temp[2] = fileLocation.toString();
			fileLocation.append(fileSaveName);
			fileFullPath.append(fileSaveName);
			 
			logger.info("to store file: " + fileLocation);
			File file = new File(fileLocation.toString());
			if(!file.exists()){
				file.createNewFile();
			}
			logger.info("file created!");
			BufferedOutputStream bf = new BufferedOutputStream(
					new FileOutputStream(file));
			bf.write(fileContent);
			bf.close();
			temp[0] = buffer.toString();
			temp[1] = fileSaveName;
			return temp;
		}
	 @RequestMapping("/produce/downloadFile.do")   
		public   ModelAndView  downloadFile(HttpServletRequest request,
				HttpServletResponse response, ModelAndView mv) throws Exception {
		 Map modelMap = new HashMap();
			String pid = request.getParameter("pid");
		    response.setCharacterEncoding("UTF-8");
			WdssFile pobj = (WdssFile)dataService.findByID(WdssFile.class, new Long(pid));
			String filePath = GlobalParamCache.getInst().getParamByKey("filepath");
			String fileName = pobj.getFilename();
			String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
			logger.debug("ext:" + ext);

			String fileDbURL = pobj.getFilepath();
			logger.debug("fileDbURL:" + fileDbURL);
			filePath += fileDbURL;
			logger.debug("test文件是否存在:" + new File(filePath).exists());

			filePath = filePath.replace("\\", "/");
			logger.debug("fileurl:" + filePath); 
			File file = new File(filePath);
			logger.debug("文件是否存在:" + file.exists());
	       
	        int fileLength = (int)file.length();
	        try{
	        	int                 length   = 0;
		        ServletOutputStream op       = response.getOutputStream();
		        ServletContext      context  = request.getSession().getServletContext();
		        String              mimetype = context.getMimeType( fileName );
		        byte[]   byteContents   =   new   byte[fileLength];   
		        FileInputStream fis   =   new   FileInputStream(file);   
		        int   retcd   =   fis.read(byteContents);   
		        fis.close();    
		        logger.debug("mimetype:" + mimetype);
		        response.setContentType(mimetype == null?"application/pdf":mimetype );
		        response.setContentLength( retcd );
		        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("gb2312"),"ISO-8859-1") + "\"" );

		        op.write(byteContents,0,retcd); 
		        op.close();
	            }catch(Exception e){
	            	e.printStackTrace();
	            }
         return null;
		}
		
}
